package com.cssw.fyzb.busi.api.acct;

import com.cssw.fyzb.core.exception.BizException;
import com.cssw.fyzb.busi.service.user.UserExtService;
import com.cssw.fyzb.core.model.dodb.UserExt;
import com.cssw.fyzb.core.model.vo.user.RedPackStatisticsVo;
import com.ydn.appserver.Action;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.appserver.annotations.Function;
import com.ydn.appserver.annotations.Parameter;
import com.ydn.appserver.annotations.Type;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * @Author: wondream
 * @Date: 2020/12/28 16:25
 */
@Function(description = "红包统计", parameters = {
        @Parameter(name = "userId", type = Type.String, description = "用户标识", required = true)
})
@Component
public class RedPackStatistics implements Action {
    private static final Logger logger = LoggerFactory.getLogger(RedPackStatistics.class);

    @Autowired
    private UserExtService userExtService;

    @Override
    public Response execute(Request request) throws Exception {
        Long userId = request.getLong("userId");
        try {
            UserExt userExt = userExtService.findById(userId);
            return Response.success().put("data", convert(userExt));
        } catch (BizException e) {
            return Response.fail(e.getErrMsg(), e.getErrCode());
        } catch (Exception e) {
            logger.error("", e);
            return Response.fail("查询红包统计失败");
        }
    }

    private RedPackStatisticsVo convert(UserExt userExt) {
        RedPackStatisticsVo vo = new RedPackStatisticsVo();
        if (null == userExt) {
            return vo;
        }
        vo.setUserId(userExt.getUserId());
        if (null != userExt.getSumRecvPack()) {
            vo.setSumRecvPack(userExt.getSumRecvPack().setScale(2, RoundingMode.HALF_UP));
        } else {
            vo.setSumRecvPack(BigDecimal.ZERO);
        }

        vo.setTotalRecvPack(userExt.getTotalRecvPack());
        if (null != userExt.getSumSendPack()) {
            vo.setSumSendPack(userExt.getSumSendPack().setScale(2, RoundingMode.HALF_UP));
        } else {
            vo.setSumSendPack(BigDecimal.ZERO);
        }
        vo.setTotalSendPack(userExt.getTotalSendPack());
        return vo;
    }
}

